package com.yc.navy.springmvc.core;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

public class HandlerResponse {

	public static void staticResource(HttpServletResponse response, String path) throws IOException {
		File f1 = new File(path);
		if(!f1.exists()) {
			send404(response, path);
			return;
		}
		try(FileInputStream fis = new FileInputStream(f1)){
			byte[] bt = new byte[fis.available()];
			fis.read();
			sendData(response, bt);
 		}
	}

	private static void sendData(HttpServletResponse response, byte[] bt) throws IOException {
		ServletOutputStream sos = response.getOutputStream();
		sos.write(bt);
		sos.flush();
	}

	public static void sendStr(HttpServletResponse response, String str) throws IOException {
		PrintWriter out = response.getWriter();
		out.print(str);
		out.flush();		
	}

	private static void send404(HttpServletResponse response, String path) throws IOException {
		PrintWriter out = response.getWriter();
		out.print("<h1>HTTP/1.1 404 File Not Found! - " + path + "</h1>");
		out.flush();
	}

	public static void sendJson(HttpServletResponse response, Object result) throws IOException {
		PrintWriter out = response.getWriter();
		out.print(result);
		out.flush();
	}
}
